#include "single_phase_BCTRAN_transformer.h"
#define PI 3.14159265358979323846 // pi
void single_phase_BCTRAN_transformer::G_Ihis_mapping()
{
    brs["12"].Gbr = GT(0);
    brs["34"].Gbr = GT(3);
    brs["13"].Gbr = -GT(1);
    brs["24"].Gbr = -GT(1);
    brs["14"].Gbr = GT(1);
    brs["23"].Gbr = GT(1);

    brs["12"].Jbr = Ihis(0);
    brs["34"].Jbr = Ihis(1);
}

void single_phase_BCTRAN_transformer::begin(param &Params)
{
    L1 = Params["L1"];
    L2 = Params["L2"];
    Im = Params["Im"] / 100;
    Le = Params["Le"];
    Vtr_1 = Params["Vtr_1"];
    Vtr_2 = Params["Vtr_2"];
    Smva = Params["Smva"];
    freq = Params["freq"];
    delt = Params["delt"];

    K = Vtr_1 / Vtr_2;
    Zb1 = Vtr_1 * Vtr_1 / Smva;
    Zb2 = Vtr_2 * Vtr_2 / Smva;

    double w = 2 * PI * freq;
    x1 = L1 * Zb1 / w;
    x2 = L2 * Zb2 / w;
    xm = 1.0 / Im * Zb1 / w;
    xe = Le * Zb1 / w;

    LT(0) = x1 + xe + xm;
    LT(1) = xm / K;
    LT(2) = xm / K;
    LT(3) = xm / (K * K) + x2;

    LT_inv_mult_2 = 0.5 * LT.inverse();

    GT = delt * LT_inv_mult_2;

    name = "BCTRAN";
    brs.set_name(name + "_brs");
    brs.Vmap["1"] = 0;
    brs.Vmap["2"] = 1;
    brs.Vmap["3"] = 2;
    brs.Vmap["4"] = 3;

    brs.add_br("1", "2", "12");
    brs.add_br("1", "3", "13");
    brs.add_br("1", "4", "14");
    brs.add_br("2", "3", "23");
    brs.add_br("2", "4", "24");
    brs.add_br("3", "4", "34");
}

void single_phase_BCTRAN_transformer::dsdyn(double delt, double simulation_time)
{
    this->delt = delt;
    GT = delt * LT_inv_mult_2;
    Ihis = GT * V_port + I_port;
    G_Ihis_mapping(); // 替代set_G_J
}

void single_phase_BCTRAN_transformer::dsout(Vector2d &V)
{
    V_port = V;
    I_port = GT * V_port + Ihis;
    // 要不要把V和I更新到每个branch上？我觉得好像没有太大必要
}